package com.dc.config.handler;

import com.dc.common.constant.CustomConstants;
import com.dc.common.utils.ShiroUtil;
import com.dc.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * @author zhuangcy
 * @date 2021/1/18
 * @description WebSession管理器
 */
@Slf4j
public class WebSessionManager extends DefaultWebSessionManager {

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = WebUtils.toHttp(request);
        String token = req.getHeader(CustomConstants.TOKEN_NAME);
        if (StringUtil.isEmpty(token)) {
            token = req.getParameter(CustomConstants.TOKEN_NAME);
        }
        if (StringUtil.isNotEmpty(token) && ShiroUtil.validateSession(token)) {
            log.debug("request method:{}, request path:{}", req.getMethod(), req.getServletPath());
            log.debug("token==========={}", token);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "Stateless request");
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, token);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return token;
        }
        return super.getSessionId(request, response);
    }
}
